package com.campus.controller;

import com.campus.domain.dto.ActivityQueryDTO;
import com.campus.domain.dto.EnrollActivityDTO;
import com.campus.domain.dto.PublishActivityDTO;
import com.campus.domain.dto.UserDTO;
import com.campus.domain.vo.ActivityVO;
import com.campus.domain.vo.EnrollStatusVO;
import com.campus.domain.vo.PageResultVO;
import com.campus.domain.vo.Result;
import com.campus.service.IActivityService;
import com.campus.utils.AliyunOssOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/activity")
public class ActivityController {

    @Autowired
    private IActivityService activityService;

    @Autowired
    private AliyunOssOperator aliyunOssOperator;

    /**
     * 发布活动
     */
    @PostMapping("/publish")
    @PreAuthorize("@ex.hasAuthority('activity:publish')")
    public Result<String> publishActivity(@RequestBody PublishActivityDTO dto) {
        // 获取当前登录用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO userDTO = (UserDTO) authentication.getPrincipal();
        Long userId = userDTO.getId();

        // 调用service发布活动
        activityService.publishActivity(dto, userId);

        return Result.ok("发布成功");
    }

    /**
     * 上传活动图片
     */
    @PostMapping("/upload/image")
    public Result uploadImage(@RequestParam("file") MultipartFile file) throws Exception {
        // 调用阿里云OSS上传图片
        String url = aliyunOssOperator.upload(file.getBytes(), Objects.requireNonNull(file.getOriginalFilename()));

        // 返回图片URL
        Map<String, String> data = new HashMap<>();
        data.put("url", url);

        return Result.ok(data);
    }

    /**
     * 获取活动列表（分页）
     */
    @GetMapping("/list")
    public Result<PageResultVO<ActivityVO>> getActivityList(ActivityQueryDTO queryDTO) {
        PageResultVO<ActivityVO> result = activityService.getActivityList(queryDTO);
        return Result.ok(result);
    }

    /**
     * 获取活动详情
     */
    @GetMapping("/detail/{id}")
    public Result<ActivityVO> getActivityDetail(@PathVariable("id") Long id) {
        ActivityVO activity = activityService.getActivityDetail(id);
        return Result.ok(activity);
    }

    /**
     * 报名活动
     */
    @PostMapping("/enroll")
    public Result<String> enrollActivity(@RequestBody EnrollActivityDTO dto) {
        // 获取当前登录用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO userDTO = (UserDTO) authentication.getPrincipal();
        Long userId = userDTO.getId();

        // 调用service报名
        activityService.enrollActivity(dto, userId);

        return Result.ok("报名成功");
    }

    /**
     * 取消报名
     */
    @PostMapping("/cancel")
    public Result<String> cancelEnroll(@RequestBody Map<String, Long> params) {
        // 获取当前登录用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO userDTO = (UserDTO) authentication.getPrincipal();
        Long userId = userDTO.getId();

        Long activityId = params.get("activityId");
        
        // 调用service取消报名
        activityService.cancelEnroll(activityId, userId);

        return Result.ok("已取消报名");
    }

    /**
     * 检查是否已报名
     */
    @GetMapping("/check-enroll/{activityId}")
    public Result<EnrollStatusVO> checkEnrollStatus(@PathVariable("activityId") Long activityId) {
        // 获取当前登录用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO userDTO = (UserDTO) authentication.getPrincipal();
        Long userId = userDTO.getId();

        boolean enrolled = activityService.checkEnrollStatus(activityId, userId);
        
        return Result.ok(new EnrollStatusVO(enrolled));
    }

    /**
     * 删除活动
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteActivity(@PathVariable("id") Long id) {
        // 获取当前登录用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO userDTO = (UserDTO) authentication.getPrincipal();
        Long userId = userDTO.getId();

        // 调用service删除活动
        activityService.deleteActivity(id, userId);

        return Result.ok("删除成功");
    }

    /**
     * 修改活动
     */
    @PutMapping("/update/{id}")
    public Result<String> updateActivity(@PathVariable("id") Long id, @RequestBody PublishActivityDTO dto) {
        // 获取当前登录用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO userDTO = (UserDTO) authentication.getPrincipal();
        Long userId = userDTO.getId();

        // 调用service修改活动
        activityService.updateActivity(id, dto, userId);

        return Result.ok("修改成功");
    }
}

